//
//  OCPBViewController.m
//  OCPB
//
//  Created by Siroj Chongkolwanont on 6/27/56 BE.
//  Copyright (c) 2556 Siroj Chongkolwanont. All rights reserved.
//

#import "OCPBViewController.h"
#import "UserInfoViewController.h"
#import <CommonCrypto/CommonDigest.h>

@interface OCPBViewController ()

@end

@implementation OCPBViewController

@synthesize loginBtn;
@synthesize usernameText;
@synthesize passwordText;
@synthesize localSpinner;

NSString* API_Key = @"Bny8p47kBs3WnlFceLkhcY9j6x88bsk6";
NSString* Secret_Key = @"j7zz(;W6R05%c=*227w0q53>|{s#;8";
NSString* timeStampObj1= @"1314592556";
NSMutableData* responseData;
NSString* authorizationData;
UITextField* currentTextField;


-(BOOL)textFieldShouldReturn:(UITextField*)textField;
{
    NSInteger nextTag = textField.tag + 1;
    // Try to find next responder
    UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
    if (nextResponder) {
        // Found next responder, so set it.
        [nextResponder becomeFirstResponder];
    } else {
        // Not found, so remove keyboard.
        [textField resignFirstResponder];
    }
    return NO; // We do not want UITextField to insert line-breaks.
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ลงชื่อเข้าใช้"
                                                      message:@"ไม่สามารถเชื่อมต่ออินเตอร์เน็ทได้ กรุณาตรวจสอบการตั้งค่าที่โทรศัพท์"
                                                     delegate:nil
                                            cancelButtonTitle:@"OK"
                                            otherButtonTitles:nil];
    [message show];
}


- (void)viewDidLoad
{
    
    long currentTime = (long)(NSTimeInterval)([[NSDate date] timeIntervalSince1970]);
    
    
    self.navigationController.navigationBar.clipsToBounds  = YES;
    timeStampObj1 = [NSString stringWithFormat:@"%ld",currentTime];
    
    currentTextField = Nil;
    
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"New_Navigation_background_320x46.png"]
                                                  forBarMetrics:UIBarMetricsDefault];
    
    //[[self navigationController] setNavigationBarHidden:YES animated:NO];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    
    [self.view addGestureRecognizer:tap];
    
    //self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pw_maze_white.png"]];
   // loginBtn
    //UIButton *myButton =  [UIButton buttonWithType:UIButtonTypeCustom];
    //[loginBtn setBackgroundColor:[UIColor blueColor]];
	// Do any additional setup after loading the view, typically from a nib.
}

-(void)dismissKeyboard {
    if(currentTextField != Nil)
        [currentTextField resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)inform_click:(id)sender {
}



- (IBAction)register_click:(id)sender {
}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSError *error = nil;
    NSDictionary* jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
    
    NSString* error_code = [jsonObject valueForKey:@"error_code"];
    
    NSString *jsonRequest =  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    NSLog(@"jsonResponse is %@", jsonRequest);
    
    if(error_code.intValue > 0)
    {
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"ลงชื่อเข้าใช้"
                                                          message:@"เข้าสู่ระบบไม่ได้"
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        
    }
    else
    {
        [self performSegueWithIdentifier:@"ToUserInfo" sender:self];
    }
    
    [localSpinner stopAnimating];
}

- (IBAction)login_click:(id)sender {

    
   
    
    if([usernameText text].length  < 13)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ลงชื่อเข้าใช้" message:@"รหัสบัตรประจำตัวประชาชนไม่ครบ 13 หลัก"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    
    NSCharacterSet* Digits = [NSCharacterSet decimalDigitCharacterSet];
    
    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    
    NSString* passStr = [passwordText text];
    
    
   if (passStr.length  < 8)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ลงชื่อเข้าใช้" message:@"รหัสผ่านต้องมีความยาวอย่างน้อย 8 หลัก"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }
    
    
    if ( [passStr rangeOfCharacterFromSet:notDigits].location == NSNotFound   || [passStr rangeOfCharacterFromSet:Digits].location == NSNotFound )
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ลงชื่อเข้าใช้" message:@"รหัสผ่านต้องประกอบด้วยตัวอักษรหรือตัวเลขอย่างน้อย 1 ตัว"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        
        return;
    }


    
    NSURL *url = [NSURL URLWithString:@"http://www.aitproject.com/demo/webservice/public/service/service/auth"];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
    
    
    [request setHTTPMethod:@"GET"];
    authorizationData = [self Authorization];
    [request setValue:authorizationData forHTTPHeaderField:@"Authorization"];
    
    [localSpinner startAnimating];
    
    NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
    if (connection) {
        responseData = [[NSMutableData alloc] init];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    currentTextField = textField;
    
}
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    currentTextField = textField;
    
    if ([string isEqualToString:@"\n"])
    {
        [textField resignFirstResponder];
    }
    
    if ([string length] == 0 && range.length > 0)
    {
        return YES;
    }
    
    
    NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
    if ([string rangeOfCharacterFromSet:notDigits].location != NSNotFound && (textField.tag == 1) )
    {
        return NO;
    }
    
    
    if (textField.tag == 1 && [textField.text length] == 13)
    {
        [textField resignFirstResponder];
        [passwordText becomeFirstResponder];
    }
    
    
    
    return YES;
    
}



- (NSString*)PasswordHashed
{
    NSMutableString *reversedString = [NSMutableString string];
    NSInteger charIndex = [Secret_Key length];
    while (charIndex > 0) {
        charIndex--;
        NSRange subStrRange = NSMakeRange(charIndex, 1);
        [reversedString appendString:[Secret_Key substringWithRange:subStrRange]];
    }
    NSLog(@"SHA1 input is %@", reversedString);
    
    //H  = sha1(secretKeyReversed + password)
    NSString* compound = [NSString stringWithFormat: @"%@%@",reversedString, passwordText.text];
    
    return [self SHA1:compound];
}

- (NSString*)Signature
{
    //Signature = SHA1(Timestamp + API_Key  + Username + PasswordHashed(Secret_Key, Password) + Secret_Key)
    
    // NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    // NSTimeInterval is defined as double
    // NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp];
    
    NSString* compound = [NSString stringWithFormat: @"%@%@%@%@%@", timeStampObj1, API_Key, usernameText.text, [self PasswordHashed], Secret_Key];
    NSLog(@"Signature input is %@", compound);
    
    NSString* signature = [self SHA1:compound];
    NSLog(@"Signature is %@", signature);
    
    return signature;
}

- (NSString*)Base64Sig
{    
    NSString* compound = [NSString stringWithFormat: @"%@:%@:%@", usernameText.text, timeStampObj1, [self Signature]];
    NSLog(@"Base64Sig input : %@", compound);
    NSString *convertedString = [self base64String:compound];
    NSLog(@"%@", convertedString);
    
    return convertedString;
}

- (NSString*)base64String:(NSString *)str
{
    NSData *theData = [str dataUsingEncoding: NSASCIIStringEncoding];
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];
    
    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;
            
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

- (NSString*)Authorization
{
    //Authorization = "OCPB" +" " + API_Key + ":" + BASE64(Username + ":" + Timestamp + ":" + Signature)
    NSString* base64Input = [NSString stringWithFormat: @"%@:%@:%@", usernameText.text, timeStampObj1, [self Signature]];
    NSLog(@"base64Input is %@", base64Input);
    NSString* compound = [NSString stringWithFormat: @"OCPB %@:%@", API_Key, [self base64String:base64Input]];
    NSLog(@"Authorization is %@", compound);
    return compound;
    
}

-(NSString*)SHA1:(NSString *)input
{
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    NSLog(@"SHA1 output is %@", output);
    
    return output;
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"ToUserInfo"])
    {    UserInfoViewController *u = (UserInfoViewController*)segue.destinationViewController;
         u.authorizationData = authorizationData;
    }
}



- (IBAction)forgot_password:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://complain.ocpb.go.th/Complain/account/PasswordRequest.aspx"]];

}
@end
